package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.CardBin;
import com.cardbaobao.cardbabyclient.model.result.CardBinResult;
import com.cardbaobao.cardbabyclient.model.result.CreditCardResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Description: 添加信用卡
 * Created by FHW
 * on 2017/11/7
 */

public class NewAddCreditCardActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_card_number)
    EditText et_card_number;
    @BindView(R.id.et_real_name)
    EditText et_real_name;
    @BindView(R.id.bt_ensure_commit)
    Button bt_ensure_commit;
    @BindView(R.id.iv_logo)
    ImageView iv_logo;
    @BindView(R.id.tv_bank)
    TextView tv_bank;

    private String card_no = "";
    private String name = "";
    private String card_type_id = "";//
    private String card_type = "";//1-储蓄卡 2-信用卡

    private boolean isCardTrue = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_credit_card_new;
    }

    @OnClick({R.id.bt_ensure_commit, R.id.tv_agreement})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_ensure_commit:
                if (card_type.equals("2")) {
                    SelfUtils.buriedClickData(Self.Action.app_click_repayment_add_creditcard_confirm,
                            Self.Action.app_click_repayment_add_creditcard_confirm_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    addCreditCard();
                } else {
                    ToastUtil.showToast("请输入正确的信用卡");
                }
                break;
            case R.id.tv_agreement:
                SelfUtils.buriedClickData(Self.Action.app_click_repayment_add_creditcard_service_agreedment,
                        Self.Action.app_click_repayment_add_creditcard_service_agreedment_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                initIntent();
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, "信用卡还款服务协议");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, URLUtil.REPAYMENT_AGREEMENT);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 12);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);
                break;
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mCurrentPageId=Self.Page.app_repayment_add_creditCard;

        title_bar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        et_card_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                card_no = s.toString();
                if (card_no.length() > 0 && RegularUtil.checkBankCard(card_no)) {
                    queryCardBin(card_no, false);
                } else {
                    isCardTrue = false;
                }

            }
        });
        et_real_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name = s.toString();
                showHighilight();
            }
        });

    }

    private void showHighilight() {
        if (isCardTrue && !name.equals("")) {
            bt_ensure_commit.setEnabled(true);
        } else {
            bt_ensure_commit.setEnabled(false);
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    /**
     * 卡 查询
     *
     * @param cardNumber
     * @param showToast
     */
    private void queryCardBin(String cardNumber, final boolean showToast) {
        Api.queryCardBin(cardNumber).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                if (showToast) {
                    dismissProgressDialog();
                    ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }
            }

            @Override
            public void onNext(String s) {
                CardBinResult result = JsonUtil.json2Object(s, CardBinResult.class);
                if (result.getCode() == Constant.SUC_CODE) {
                    //成功
                    CardBin bin = result.getData();
                    ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL + bin.getBank_logo(), iv_logo, R.mipmap.img_default_square);
                    tv_bank.setText(bin.getBank_name());
                    card_type_id = bin.getBank_id();
                    card_type = bin.getBank_type();
                    isCardTrue = true;
                    showHighilight();

                } else {
                    if (showToast) {
                        dismissProgressDialog();
                        ToastUtil.showToast(result.getMsg());
                    }
                }
            }
        });
    }


    /**
     * 添加信用卡还款卡
     */
    private void addCreditCard() {
        showProgressDialog(false);
        Api.addCreditCard(mApplication.getUser().getID(), card_type_id, name, card_no)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        CreditCardResult creditCardResult = JsonUtil.json2Object(s, CreditCardResult.class);
                        if (creditCardResult.getCode() == Constant.SUC_CODE) {
                            Intent addCardIntent= new Intent(NewAddCreditCardActivity.this,
                                    NewAddCreditCardSuccessActivity.class);
                            addCardIntent.putExtra("creditCard", creditCardResult.getData());
                            addCardIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                            startActivity(addCardIntent);
                            finish();
                        } else {
                            ToastUtil.showToast(creditCardResult.getMsg());
                        }

                    }
                });
    }

}
